<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogUpdateApply.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogUpdateApply.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog(false)"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="200"
      style="padding-right: 10px; overflow: auto"
    >
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 60px; text-indent: 2em; line-height: 30px; font-weight: 600"
        >项目基础信息</el-row
      >
      <el-row justify="start" style="margin-top: 10px">
        <!-- <el-col :span="12">
          <el-form-item
            :label="dialogUpdateApply.type == 1 ? '建筑市场监管平台项目编号' : '行业主管部门项目编号'"
            prop="industryPrjNum"
          >
            <el-input
              v-model="formData.industryPrjNum"
              :placeholder="
                dialogUpdateApply.type == 1 ? '请输入建筑市场监管平台项目编号' : '请输入行业主管部门项目编号'
              "
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="用地许可证编号" prop="buildPlanNum">
            <el-input v-model="formData.buildPlanNum" placeholder="请输入用地许可证编号" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="施工许可证编号" prop="builderLicences">
            <el-input v-model="formData.builderLicences" placeholder="请输入施工许可证编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工许可证发证日期" prop="builderLicencesGrantDate">
            <el-date-picker
              v-model="formData.builderLicencesGrantDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="施工许可证有效期限" prop="builderLicencesTermDate">
            <el-date-picker
              v-model="formData.builderLicencesTermDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="中标通知书编号" prop="letterAcceptanceNum">
            <el-input v-model="formData.letterAcceptanceNum" placeholder="请输入中标通知书编号" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="招标标段编号" prop="biddingSectionNum">
            <el-input v-model="formData.biddingSectionNum" placeholder="请输入招标标段编号" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="所在城市" prop="areaCode">
            <el-cascader v-model="formData.areaCode" placeholder="请选择项目归属地区" :options="areaoptions"
              @change="handleCascaderChange" />
          </el-form-item>
        </el-col> -->

        <el-col :span="12">
          <el-form-item label="中标合同价格(工程造价)" prop="contractAmount">
            <!-- <el-input
              v-model="formData.contractAmount"
              type="number"
              placeholder="请输入中标合同价格(工程造价)(万元)"
            /> -->
            <money-input v-model="formData.contractAmount" unit="万元"></money-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同开工日期" prop="contractStartDate">
            <el-date-picker
              v-model="formData.contractStartDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际开工日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同竣工日期" prop="contractEndDate">
            <el-date-picker
              v-model="formData.contractEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledEndDate"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="多地施工点位" prop="positionCount">
            <el-input-number v-model="formData.positionCount" :min="1" :max="12" placeholder="请输入多地施工点位" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系人" prop="linkMan">
            <el-input v-model="formData.linkMan" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系电话" prop="linkPhone">
            <el-input v-model="formData.linkPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="上传中标通知书/施工合同" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">确认修改</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import MoneyInput from "@/components/MoneyInput/index.vue";
import { Except, Ride } from "@/utils/decimal";
import { GetProjectForm, CreateUpdateProjectApply } from "@/api/project/projectInfo/index";
import { ProjectUpdateApplyForm } from "@/api/project/projectInfo/types";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";
import moment from "moment";

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
//行政区划
const areaoptions = getDicts("areaTrees").filter((item: { value: number }) => item.value === 540000);

//上传文件列表
const fileList = ref<UploadUserFile[]>([]);

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogUpdateApply: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
      type: 1,
    }),
  },
});

const { dialogUpdateApply } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<ProjectUpdateApplyForm>({});
const addOrEditFormRef = ref(ElForm);

const disabledEndDate = (time: Date) => {
  if (formData.contractStartDate) {
    return time.getTime() <= new Date(formData.contractStartDate).getTime();
  }
  return time.getTime() > new Date(moment().format("YYYY-MM-DD")).getTime();
};
//表单验证规则
const validatorAttachment = function (_rule: any, _value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传中标通知书/施工合同附件!"));
    return;
  } else {
    callback();
  }
};

const rules = reactive<FormRules<ProjectUpdateApplyForm>>({
  areaCode: [{ required: true, message: "项目归属地不能为空", trigger: "blur" }],
  builderLicences: [{ required: true, message: "施工许可证不能为空", trigger: "blur" }],
  builderLicencesGrantDate: [{ required: true, message: "施工许可证发证日期不能为空", trigger: "blur" }],
  builderLicencesTermDate: [{ required: true, message: "施工许可证有效期不能为空", trigger: "blur" }],
  contractAmount: [{ required: true, message: "中标合同金额不能为空", trigger: "blur" }],
  startDate: [{ required: true, message: "实际开工日期不能为空", trigger: "blur" }],
  contractStartDate: [{ required: true, message: "合同开工日期不能为空", trigger: "blur" }],
  contractEndDate: [
    {
      required: true,
      message: "合同竣工日期不能为空",
      trigger: "blur",
    },
    {
      trigger: "blur",
      validator(_rule, value, callback, _source, _options) {
        if (value && formData.contractStartDate) {
          if (new Date(value).getTime() < new Date(formData.contractStartDate).getTime()) {
            callback(new Error("合同开工日期不能早于实际开工日期"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
    },
  ],
  positionCount: [{ required: true, message: "请输入多地施工点位", trigger: "blur" }],
  linkMan: [{ required: true, message: "联系人姓名不能为空", trigger: "blur" }],
  linkPhone: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话号码",
      trigger: "blur",
    },
  ],
  attachments: [
    {
      required: true,
      message: "请上传项目文件",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
});
/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}
const initForm = async function () {
  if (dialogUpdateApply.value.id) {
    loading.value = true;
    let res = await GetProjectForm(dialogUpdateApply.value.id);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        res.data.contractAmount = Except(res.data.contractAmount, 10000);
        Object.assign(formData, res.data);
        if (res.data.attachmentFiles) {
          let list = Array<any>();
          res.data.attachmentFiles.forEach((item: any) => {
            list.push({
              name: item.friendlyName,
              url: item.objectFilePath,
              status: "success",
              uid: item.id,
            });
          });
          fileList.value = list;
        }
      } else {
      }
    } else {
    }
  }
};

//城市联动赋值
const handleCascaderChange = (value: any) => {
  if (value.length == 3) {
    formData.cityCode = value[1];
    formData.areaCode = value[2];
  }
  // 在这里可以对选中的值进行进一步处理
};

watch(
  () => dialogUpdateApply.value.visible,
  () => {
    if (dialogUpdateApply.value.visible) {
      initForm();
    }
  }
);
onMounted(async () => {
  initScreen();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        formData.attachments = new Array<any>();
        fileList.value.map((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              formData.attachments?.push({ attachmentId: item.response.data });
            } else {
              formData.attachments?.push({ attachmentId: item.uid });
            }
          }
        });
      }
      let submitForm = Object.assign({}, formData);
      submitForm.contractAmount = Ride(formData?.contractAmount ?? 0, 10000);
      CreateUpdateProjectApply(dialogUpdateApply.value.id, submitForm)
        .then((res) => {
          if (res.type === 0) {
            if (res.success === true) {
              ElMessage.success(res.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(res.msg);
            }
          } else {
            ElMessage.warning(res.msg);
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}

:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
